package explorer;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aliang.auto.R;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import app.auto.runner.base.BroadcastBuilder;
import app.auto.runner.base.DialogUtil;
import app.auto.runner.base.SPrefUtil;
import app.auto.runner.base.intf.ListBuilder;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.utility.PermissionActivity;
import app.auto.runner.base.utility.ReadFileUtil;
import app.auto.runner.base.utility.ToastUtil;

public class ExplorerActivity extends PermissionActivity {
    private final String CACHE_PATH = "CACHE_PATH";
    String root;
    List list;
    String now;
    BaseAdapter baseadapter;
    private long mExitTime;
    private int pos;
    public int max = 0;
    public int min = 0;
    public List<Integer> set = new ArrayList<Integer>();
    private int firstvisibleitem;

    Map<String, Integer> mins = new TreeMap<String, Integer>();

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
//        permission();
        setContentView(R.layout.explorer_activity_main);

        final Map m = (Map) getIntent().getSerializableExtra("params");
        final String cachepath = (String) SPrefUtil.getValue(this.CACHE_PATH);
        String cache = m == null ? "false" : (String) m.get("cacheEnable");
        final String emptyFileCheckable = m == null ? "false" : (String) m.get("EmptyFileCheckable");

        String input = "";

        if (!TextUtils.isEmpty(input)) {
            root = new File(input).getAbsolutePath();

        } else {
            root = StorageUtil.getPrimaryStoragePath(this);
        }

        if (!TextUtils.isEmpty(cachepath) && Boolean.parseBoolean(cache)) {
            now = new File(cachepath).getAbsolutePath();

        } else {
            now = StorageUtil.getPrimaryStoragePath(this);
        }

        ((ListView) findViewById(R.id.listview)).setAdapter(baseadapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return list == null ? 0 : list.size();
            }

            @Override
            public Object getItem(int position) {
                return list.get(position);
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(ExplorerActivity.this).inflate(R.layout.explorer_icon_string_item, null);
                }
                final File file = (File) getItem(position);
                if (file.isDirectory() && convertView.findViewById(R.id.image) != null) {
                    ((ImageView) convertView.findViewById(R.id.image)).setImageResource(R.drawable.explorer_timg);
                } else {
                    ((ImageView) convertView.findViewById(R.id.image)).setImageResource(R.mipmap.explorer_wbwj);
                }
                ((TextView) convertView.findViewById(R.id.name)).setText(file.getName());
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (file.isDirectory()) {

                            mins.put(file.getParent(), ExplorerActivity.this.firstvisibleitem);
                            access(file.getAbsolutePath());
                        } else {

                            String cache = getIntent().getStringExtra("cacheEnable");
                            if (!TextUtils.isEmpty(cache) && Boolean.parseBoolean(cache)) {
                                SPrefUtil.putValue(CACHE_PATH, file.getParent());
                            }
                            if (emptyFileCheckable != null && emptyFileCheckable.equals("true")) {
                                if (file.length() == 0 || ReadFileUtil.readsd(ExplorerActivity.this, file.getAbsolutePath()).trim().equals("")) {
                                    ToastUtil.live(ExplorerActivity.this).setDuration(Toast.LENGTH_SHORT).toast("空文件");
                                    return;
                                }
                            }
//                            sendBroadcast(new Intent(getIntent().getAction()+"_out").putExtra("params", getIntent().getSerializableExtra("params")).putExtra("task", getIntent().getStringExtra("task")).putExtra("output", "" + file.getAbsolutePath()));
                            finish();
                            BroadcastBuilder.build().sendAction(getIntent().getAction() + "_out", getIntent().getStringExtra("task"), getActvity(), MapBuilder.build().add("output", file.getAbsolutePath()), BroadcastBuilder.Starttype.broadcast);
                        }
                    }
                });


                return convertView;
            }
        });
        if (PermissionUtil.checkPermission(ExplorerActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            new Handler(Looper.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message message) {
                    access(now);
                    return false;
                }
            }).sendEmptyMessage(0);
        }
        ((EditText) findViewById(R.id.createfile)).addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                access(s.toString(), now, true);
//                if (TextUtils.isEmpty(s.toString())) {
//                    findViewById(R.id.right).setVisibility(View.INVISIBLE);
//                } else
//                    findViewById(R.id.right).setVisibility(View.VISIBLE);

            }
        });
        ((ListView) findViewById(R.id.listview)).setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                ExplorerActivity.this.firstvisibleitem = firstVisibleItem;
            }
        });
        findViewById(R.id.right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                final String createfile = ((TextView) findViewById(R.id.createfile)).getText().toString();
                if (TextUtils.isEmpty(createfile)) {
                    return;
                }
                target_add_dialog = DialogUtil.showDialog("新建", v, android.R.color.holo_orange_light, ListBuilder.build().add("文件夹").add("文件").get(), new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String text = ((TextView) view.findViewById(R.id.name)).getText().toString();
                        if (text.equals("文件夹")) {
                            try {
                                new File(now + "/" + createfile).mkdirs();
                            } catch (Exception e) {
                                ToastUtil.live((Activity) v.getContext()).toast("创建发生错误");
                                e.printStackTrace();
                            }
                            List<File> files = access(now);
                            int i = Collections.binarySearch(files, new File(now + "/" + createfile), new Comparator<File>() {
                                @Override
                                public int compare(File o1, File o2) {
                                    return o1.getAbsolutePath().compareTo(o2.getAbsolutePath());
                                }
                            });
                            ((ListView) findViewById(R.id.listview)).setSelection(i);
                        } else if (text.equals("文件")) {
                            try {
                                new File(now + "/" + createfile).createNewFile();
                            } catch (IOException e) {
                                ToastUtil.live((Activity) v.getContext()).toast("创建发生错误");
                                e.printStackTrace();
                            }
                            List<File> files = access(now);
                            int i = Collections.binarySearch(files, new File(now + "/" + createfile), new Comparator<File>() {
                                @Override
                                public int compare(File o1, File o2) {
                                    return o1.getAbsolutePath().compareTo(o2.getAbsolutePath());
                                }
                            });
                            ((ListView) findViewById(R.id.listview)).setSelection(i);
                        }
                        access(createfile, now, true);
                        target_add_dialog.dismiss();
                        target_add_dialog.cancel();
                        target_add_dialog = null;
                    }
                }, R.layout.title_listview);
                target_add_dialog.show();
            }
        });
    }

    Dialog target_add_dialog;

    private void permission() {
        new PermissionUtil().checkAndRequestPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE, 0, new PermissionUtil.PermissionCheckCallBack() {
            @Override
            public void ungranted() {
                permission();
            }

            @Override
            public void onHasPermission() {

            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {

            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {

            }
        });
    }

    private List<File> access(String access) {
        return access("", access, true);
    }

    private List<File> access(final String key, String access, boolean notified) {
        if (root.startsWith(access) && !root.equals(access)) {
            Toast.makeText(this, "到顶", Toast.LENGTH_SHORT).show();
            return null;
        }

        this.now = access;
        File[] file = new File(access).listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if (!TextUtils.isEmpty(key)) {

                    if (pathname.getName().toLowerCase().contains(key.toLowerCase())) {
                        return true;
                    } else {
                        return false;
                    }
                }

                return true;

            }
        });
        if(file==null){
            return new ArrayList();
        }
        List<File> list = Arrays.asList(file);
        Collections.sort(list, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() || o2.isFile()) {
                    return -1;
                } else if (o1.isFile() || o2.isDirectory()) {
                    return 1;
                } else {
                    return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
                }
            }
        });
        if (notified) {
            this.list = list;
            if (!TextUtils.isEmpty(key)) {
                if (list.size() > 0) {
                    ((ListView) findViewById(R.id.listview)).setSelection(0);
                }

            }
            baseadapter.notifyDataSetChanged();

        }
        return list;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        access(now);

    }

    @Override
    public void onBackPressed() {
        if (!TextUtils.isEmpty(((TextView) findViewById(R.id.createfile)).getText().toString())) {
            ((TextView) findViewById(R.id.createfile)).setText("");
            return;
        }
        if (!now.equals(root) && now.length() > root.length()) {

            access(new File(now).getParentFile().getAbsolutePath());

        } else {
            super.onBackPressed();

//            if ((System.currentTimeMillis() - mExitTime) > 2000) {
//                //大于2000ms则认为是误操作，使用Toast进行提示
//                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
//                //并记录下本次点击“返回键”的时刻，以便下次进行判断
//                mExitTime = System.currentTimeMillis();
//            } else {
//            小于2000ms则认为是用户确实希望退出程序 - 调用System.exit() 方法进行退出
//                super.onBackPressed();
//            }
        }
    }
}
